//
//  PayMoneyViewController.m
//  YunGou
//
//  Created by macbook on 16/5/20.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "PayMoneyViewController.h"
#import "GoodsNumView.h"
#import <Masonry.h>
#import "NSObject+Tools.h"
#import "PayHeaderView.h"
#import "PayMoneyOrderCell.h"
#import "NSString+Frame.h"
#import <Pingpp.h>

#define kUrlScheme      @"YunGou"

@interface PayMoneyViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,assign) BOOL isFold;
@property (weak, nonatomic)  IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSArray *payTitleArray;
@property (nonatomic,strong) NSArray *payImageArray;
@property (nonatomic,strong) GoodsNumView *goodsNumHeader;
@property (nonatomic,strong) PayHeaderView *payTypeHeader;
@property (weak, nonatomic) IBOutlet UILabel *payPriceLabel;
//实付款
@property (nonatomic,assign) NSInteger totalPrice;
//余额支付价格
@property (nonatomic,assign) CGFloat balance;
//三方支付价格
@property (nonatomic,assign) CGFloat thirdPayPrice;

@property (nonatomic,strong) NSString *channel;
@property (nonatomic,strong) NSArray *channelArray;

//选择的selectedSection
@property (nonatomic,assign) NSInteger selectedSection;
//选择的selectedRow
@property (nonatomic,assign) NSInteger selectedRow;

@property (nonatomic,assign) BOOL isThis;

@end

@implementation PayMoneyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _payTitleArray = @[@"微信支付",@"支付宝支付"];
    _channelArray = @[@"wx",@"alipay"];
    _payImageArray = @[@"shouye_cz_wxzf",@"shouye_cz_zfbzf"];
    
    _selectedSection = -1;
    _selectedRow = -1;
    
    _totalPrice = 0;
    for (ProductModel *model in _orderArray) {
        _totalPrice += model.goods_num;
    }
    _payPriceLabel.text = [NSString stringWithFormat:@"￥%ld",_totalPrice];
}

//确认支付
- (IBAction)surePayClicked:(id)sender {
    if (_selectedSection == -1 && _selectedRow == -1) {
        [MBProgressHUD showError:@"请选择支付方式"];
        return;
    }
    if (_selectedSection == 1) {
        [NetWorkTool payMoneyWithCode:_orderId success:^(id object) {
            if ([object[@"code"] integerValue] == 1) {
                [MBProgressHUD showSuccess:@"支付成功"];  
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else{
                [MBProgressHUD showError:object[@"data"]];
            }
        } failure:^(NSError *error) {
            FZLog(@"%@",error);
        }];
    }else if (_selectedSection == 2) {
        __weak typeof(self) ws = self;
        [NetWorkTool payWithOrderNo:_orderId Channel:_channelArray[_selectedRow] amount:[NSString stringWithFormat:@"%ld",_totalPrice] success:^(id object) {
            NSString *charge = object;
            [Pingpp createPayment:charge
                   viewController:ws
                     appURLScheme:kUrlScheme
                   withCompletion:^(NSString *result, PingppError *error) {
                       NSLog(@"completion block: %@", result);
                       if (error == nil) {
                           NSLog(@"PingppError is nil");
                       } else {
                           NSLog(@"PingppError: code=%lu msg=%@", (unsigned  long)error.code, [error getMsg]);
                       }
                   }];
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        if (!_isFold) {
            return 0;
        }
        return _orderArray.count;
    }
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        ProductModel *model = _orderArray[indexPath.row];
        CGFloat renciWidth = [[NSString stringWithFormat:@"%ld人次",model.goods_num] widthWithFont:[UIFont systemFontOfSize:13]];
        CGFloat height = [model.title heightWithFont:[UIFont systemFontOfSize:12] withinWidth:ScreenWidth - 34 - renciWidth];
        return 44 - 16 + height;
    }return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *baseCell = nil;
    if (indexPath.section == 0) {
        PayMoneyOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell.productModel = _orderArray[indexPath.row];
        baseCell = cell;
    }else if (indexPath.section == 1){//福分支付
        baseCell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        UILabel *moneyLabel = [baseCell.contentView viewWithTag:1];
        UILabel *payTypeLabel = [baseCell.contentView viewWithTag:2];
        if (indexPath.row == 0) {
            payTypeLabel.text = @"福分支付";
            moneyLabel.text = @"（可用福分1000 可抵现1元）";
        }else{//余额支付
            payTypeLabel.text = @"余额支付";
            [NetWorkTool userAccountWithSuccess:^(id object) {
                if ([object[@"code"] integerValue] == 1) {
                    moneyLabel.text = [NSString stringWithFormat:@"（账户余额：%@元）",object[@"data"]];
                    if ([object[@"data"] isEqualToString:@"0.00"]) {
                        baseCell.userInteractionEnabled = NO;
                    }else{
                        baseCell.userInteractionEnabled = YES;
                    }
                }
            } failure:^(NSError *error) {
                
            }];
        }
        
        UIButton *squareBtn = [baseCell.contentView viewWithTag:3];
        if (_selectedSection == 1) {
            if (!_isThis) {
                [squareBtn setBackgroundImage:[UIImage imageNamed:@"zf_weixuan"] forState:UIControlStateNormal];
            }else{
                [squareBtn setBackgroundImage:[UIImage imageNamed:@"zf_yixuan"] forState:UIControlStateNormal];
            }
        }else{
            [squareBtn setBackgroundImage:[UIImage imageNamed:@"zf_weixuan"] forState:UIControlStateNormal];
        }
    }else{
        baseCell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
        UILabel *payTitleLabel = [baseCell.contentView viewWithTag:2];
        payTitleLabel.text = _payTitleArray[indexPath.row];
        UIImageView *payImageView = [baseCell.contentView viewWithTag:1];
        payImageView.image = [UIImage imageNamed:_payImageArray[indexPath.row]];
        
        UIImageView *rightImageView = [baseCell.contentView viewWithTag:3];
        if (_selectedSection == indexPath.section) {
            if (_selectedRow == indexPath.row) {
                if (!_isThis) {
                    rightImageView.hidden = YES;
                }else{
                    rightImageView.hidden = NO;
                }
            }else{
                rightImageView.hidden = YES;
            }
        }else{
            rightImageView.hidden = YES;
        }
    }
    
    if (indexPath.section == 0) {
        baseCell.selectionStyle = UITableViewCellSeparatorStyleNone;
    }
    return baseCell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0 || section == 2) {
        return 44;
    }return 0.01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return self.goodsNumHeader;
    }else if (section == 2){
        return self.payTypeHeader;
    } return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section != _selectedSection || indexPath.row != _selectedRow) {
        
        if (_selectedRow != -1 && _selectedSection != -1) {
            _isThis = NO;
            [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_selectedRow inSection:_selectedSection]] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        
        _isThis = YES;
        _selectedSection = indexPath.section;
        _selectedRow = indexPath.row;
        [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)foldClicked{
    _isFold = !_isFold;
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    if (!_isFold) {
        _goodsNumHeader.foldImage.image = [UIImage imageNamed:@"fl_arrow_xia"];
    }else{
        _goodsNumHeader.foldImage.image = [UIImage imageNamed:@"zhifu_arrow_shang"];
    }
}

- (GoodsNumView *)goodsNumHeader{
    if (!_goodsNumHeader) {
        _goodsNumHeader = [GoodsNumView nibInitializtion];
        _goodsNumHeader.userInteractionEnabled = YES;
        _goodsNumHeader.goodsNumberLabel.text = [NSString stringWithFormat:@"商品数量 %ld",_orderArray.count];
        UITapGestureRecognizer *headTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(foldClicked)];
        [_goodsNumHeader addGestureRecognizer:headTap];
    }
    return _goodsNumHeader;
}

- (PayHeaderView *)payTypeHeader{
    if (!_payTypeHeader) {
        _payTypeHeader = [PayHeaderView nibInitializtion];
    }
    return _payTypeHeader;
}

@end
